//
//  LeftSideDrawerViewController.m
//  SAP
//
//  Created by 中矿科技有限公司 on 17/9/8.
//  Copyright © 2017年 中矿科技有限公司. All rights reserved.
//

#import "LeftSideDrawerViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "SATabViewController.h"
#import "ChangePassViewController.h"
#import "SAPresonViewController.h"

#import "PassWordTool.h"
#import "UIView+Tap.h"

@interface LeftSideDrawerViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate>

@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic,strong) NSArray * drawerWidths;

@end

@implementation LeftSideDrawerViewController
{
    UIView *_headView;
    UIImageView *_headImageView;
    UILabel *_nameLabel;
    NSMutableArray *textArray;
    NSMutableArray *imageArray;
     UILabel* cacheLabel;
    MBProgressHUD* HUD;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    textArray =[NSMutableArray arrayWithArray:@[@"修改密码",@"清除缓存",@"版本号",@"退出登录"]];
    
    imageArray =[NSMutableArray arrayWithArray:@[@"密码",@"清除缓存",@"版本",@"退出"]];
    
    self.automaticallyAdjustsScrollViewInsets =NO;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self customUI];

}

-(void)customUI{
    
    if(HUD)HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT-20) style:UITableViewStyleGrouped];
    
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.view addSubview:self.tableView];
    [self.tableView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
    
    UIColor * tableViewBackgroundColor;
    tableViewBackgroundColor = [UIColor colorFromHex:@"f1f2f5"];
    [self.tableView setBackgroundColor:[UIColor whiteColor]];
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [self.view setBackgroundColor:[UIColor colorFromHex:@"f1f2f5"]];
    
    [self addHeadView];
}

-(void)addHeadView
{
    _headView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 122)];
    _headView.backgroundColor =[UIColor colorFromHex:@"f1f2f5"];
    _tableView.tableHeaderView =_headView;//设置头视图;
    _headImageView =[[UIImageView alloc]initWithFrame:CGRectMake(13,_headView.center.y-23, 55, 55)];
//    if ([[[UserManager sharedInstance] getAvatar] isEqualToString:@""]) {
        _headImageView.image =[UIImage imageNamed:@"用户"];
//    }else{
//    [_headImageView sd_setImageWithURL:[NSURL URLWithString:[[UserManager sharedInstance] getAvatar]] placeholderImage:[UIImage imageNamed:@"用户"]];
//}
    _headImageView.userInteractionEnabled =YES;
    _headView.userInteractionEnabled =YES;
   // UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(photoLibray:)];
   // [_headImageView addGestureRecognizer:tap];
    
    _headImageView.layer.cornerRadius =_headImageView.frame.size.width/2;//设置成圆形的
    _headImageView.clipsToBounds =YES;
    _nameLabel =[[UILabel alloc]initWithFrame:CGRectMake(78,_headView.center.y-15 ,150, 30)];
    
    _nameLabel.font =[UIFont systemFontOfSize:15];
    _nameLabel.text =[[UserManager sharedInstance] getNickname];
    _nameLabel.textAlignment =NSTextAlignmentCenter;
    _nameLabel.text =[PassWordTool readPassWord:@"com.company.app.username"];
    UILabel *lineLabel =[UITool labelWithTitle:@"" frame:CGRectMake(0, _headView.frame.size.height-1, SCREEN_WIDTH, 1) font:[UIFont systemFontOfSize:11] textColor:[UIColor whiteColor] backColor:[UIColor colorFromHex:@"cccccc"]];
    
    [_headView addSubview:lineLabel];
    [_headView addSubview:_headImageView];
    [_headView addSubview:_nameLabel];
    
    DefineWeakSelf;
    [_headView setTapActionWithBlock:^{
        SAPresonViewController *saPresonVC =[[SAPresonViewController alloc]init];
        //[self onClicked];
        UITabBarController * vcTabBar  = (UITabBarController*)weakSelf.mm_drawerController.centerViewController;
        NSArray * arrVCS = [vcTabBar viewControllers];
        UINavigationController *vc =[arrVCS objectAtIndex:vcTabBar.selectedIndex];
        [vc pushViewController:saPresonVC animated:NO];
    }];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return textArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cell_id = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;// 箭头
    cell.textLabel.font = [UIFont systemFontOfSize:16.0f];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    cell.textLabel.text =textArray[indexPath.row];
    cell.imageView.image =[UIImage imageNamed:imageArray[indexPath.row]];
    
    if ([textArray[indexPath.row] isEqualToString:@"清除缓存"]) {
        cacheLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - SIZETONORMAL(120), (SIZETONORMAL(130) - SIZETONORMAL(44)) / 2, SIZETONORMAL(50), SIZETONORMAL(44))];
        [cacheLabel setBackgroundColor:[UIColor clearColor]];
        [cacheLabel setTextColor:[UIColor colorWithWhite:161.0/255.0 alpha:1.0]];
        [cacheLabel setText:[NSString stringWithFormat:@"%.1f M",[self folderSizeAtPath:PATH_CACHE_FOLDER]]];
        [cacheLabel sizeToFit];
        CGRect cacheFrame = cacheLabel.frame;
        cacheFrame.origin.x = 280 - SIZETONORMAL(100) - cacheLabel.frame.size.width;
        cacheLabel.frame = cacheFrame;
        [cell addSubview:cacheLabel];
    }
    if ([textArray[indexPath.row] isEqualToString:@"版本号"]) {
        UILabel *label = [[UILabel alloc] init];
        label.frame =CGRectMake(SCREEN_WIDTH-100, 0, 100, 40);
        label.text = [NSString stringWithFormat:@"Version:%@",XcodeAppVersion];
        label.textAlignment = NSTextAlignmentRight;
        label.textColor =[UIColor colorWithWhite:161.0/255.0 alpha:1.0];
        cell.accessoryView = label;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([textArray[indexPath.row] isEqualToString:@"退出登录"]) {
        [self onClickedExitCell];
    }
    if ([textArray[indexPath.row] isEqualToString:@"清除缓存"]){
        //清除缓存
        if ([self folderSizeAtPath:PATH_CACHE_FOLDER] < 0.3) {
            [MBProgressHUD showSuccess:@"暂不需要清理"];
        }else{
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定清除缓存?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//            [alertView setTag:ALERT_CLEAR];
            [self.view addSubview:alertView];
            [alertView show];
        }
    }
    if ([textArray[indexPath.row] isEqualToString:@"修改密码"]) {
        ChangePassViewController *changePassVC =[[ChangePassViewController alloc]initWithNibName:@"ChangePassViewController" bundle:nil];
        //[self onClicked];
        UITabBarController * vcTabBar  = (UITabBarController*)self.mm_drawerController.centerViewController;
        NSArray * arrVCS = [vcTabBar viewControllers];
        UINavigationController *vc =[arrVCS objectAtIndex:vcTabBar.selectedIndex];
        [vc pushViewController:changePassVC animated:NO];
    }
    
}
-(void)onClickedExitCell{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定要退出登陆" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [UserManager sharedInstance].lastConnectionStatus =ZYDConnectionStatusMannualLogout;
        [[AppDelegate sharedAppDelegate] enterLoginUI];
    }];
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}



-(void)onClicked{
    SATabViewController * center = [[SATabViewController alloc] init];
    [self.mm_drawerController
     setCenterViewController:center
     withCloseAnimation:NO
     completion:nil];
}

#pragma mark 缓存清除
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
//单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//删除指定文件夹下内容
- (void) removeFolderByPath:(NSString*) folderPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:folderPath error:NULL];
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        [fileManager removeItemAtPath:[folderPath stringByAppendingPathComponent:filename] error:NULL];
    }
}
#pragma mark- AlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        //清除缓存
        if (buttonIndex == 1) {
            HUD.mode = MBProgressHUDModeIndeterminate;
            HUD.label.text = @"清理中...";
            HUD.minShowTime = 0.5;
            
            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0), ^{

                dispatch_async(dispatch_get_main_queue(), ^{
                    [HUD showAnimated:YES];
                    [self removeFolderByPath:PATH_CACHE_FOLDER];
                    
                });

                dispatch_async(dispatch_get_main_queue(), ^{
                    cacheLabel.text = [NSString stringWithFormat:@"%.1f M",[self folderSizeAtPath:PATH_CACHE_FOLDER]];
                    [cacheLabel sizeToFit];
                    CGRect cacheFrame = cacheLabel.frame;
                    cacheFrame.origin.x = SCREEN_WIDTH - SIZETONORMAL(100) - cacheLabel.frame.size.width;
                    cacheLabel.frame = cacheFrame;
                    [MBProgressHUD showSuccess:@"清理完成"];
                    
                });
            });
        }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 获取当前显示的视图
 
 @return 返回当前视图
 */
- (UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows){
            if (tmpWin.windowLevel == UIWindowLevelNormal){
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
